#include "swagme.h"
#include "Sprite.h"

#define FRAMES_PER_ANIM 3

Sprite::Sprite(const char *file) {
  int len = strlen(file);
  SpriteImageFile = new char[len];
  if (SpriteImageFile)
    strcpy(SpriteImageFile,file);
  else
    cout << "SpriteImageFile not allocated\n" << endl;

  pSpriteSurface = IMG_Load(SpriteImageFile);
  if (!pSpriteSurface) {
    printf("Unable to load sprite image: %s\n", SDL_GetError());
    exit(1);
  }

  Frame.x=0;
  Frame.y=0;
  Frame.w=SPRITE_SIZE_X;
  Frame.h=SPRITE_SIZE_Y;
}

int Sprite::Blit(SDL_Surface *dst, int x, int y) {
  if (!dst)
    cout << "Sprite error: invalid destination surface\n" << endl;
  if (!pSpriteSurface)
    cout << "Sprite error: Sprite not initialized\n" << endl;
  SDL_Rect dstRect;
  dstRect.x = x;
  dstRect.y = y;
  dstRect.w = Frame.w;
  dstRect.h = Frame.h;
  return SDL_BlitSurface(pSpriteSurface, &Frame, dst, &dstRect);
}

int Sprite::Draw(int animationIndex, int frameIndex, SDL_Surface *dst, int x, int y) {
  Frame.x = Frame.w * frameIndex;
  Frame.y = Frame.h * animationIndex;
  return Blit(dst, x, y);
}

Sprite::~Sprite() {
  if (SpriteImageFile) delete[] SpriteImageFile;
  if (pSpriteSurface) SDL_FreeSurface(pSpriteSurface);
}
